<?php
// +----------------------------------------------------------------------
// | YFCMF [ WE CAN DO IT MORE SIMPLE]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2020 http://yfcmf.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: rainfer <rainfer520@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\controller\setting;

use app\admin\model\setting\AuthRule as AuthRuleModel;
use app\admin\model\setting\Admin as AdminModel;
use app\admin\model\setting\AuthGroup as AuthGroupModel;
use app\admin\controller\Base;

/**
 * 管理员管理
 * @author rainfer520@qq.com
 */
class Admin extends Base
{
    /**
     * 列表
     *
     * @route('admin/list')
     */
    public function index()
    {
        if ($this->request->isPost()) {
            //搜索参数
            $isEnabled = input('isEnabled', -1, 'intval');
            $userName = input('userName', '', 'trim');
            $phone = input('phone', '', 'trim');
            $realName = input('realName', '', 'trim');
            $startTime = input('startTime', '', 'strtotime');
            $endTime = input('endTime', '', 'strtotime');
            $order = input('order/a', 'a.id desc');
            $page = input('page', 1, 'intval');
            $psize = input('psize', 10, 'intval');

            $lists = AdminModel::getLists($userName, $phone, $realName, $startTime, $endTime, $isEnabled, $order, $page, $psize);
            $result['total'] = AdminModel::getTotal($userName, $phone, $realName, $startTime, $endTime, $isEnabled);
            $result['data'] = $lists;
            ajax_return_ok($result);
        }
    }


    /**
     * 取登录用户信息
     *
     * @route('admin/getAdmin')
     */
    public function getAdmin()
    {
        $user = $this->user;
        $access = AuthRuleModel::getAuthByGroupIdToTree($user['groupId']);
        $routers = AuthRuleModel::getRouters($access);
        $user['access'] = $routers;
        $group = AuthGroupModel::find($user['groupId']);
        $user['group'] = $group['title'];
        ajax_return_ok($user);
    }


    /**
     * 详情
     *
     * @route('admin/getInfo')
     */
    public function getInfo()
    {
        $uid = input('id', 0, 'intval');
        if ($uid == 0) {
            ajax_return_error('参数有误！');
        }
        $info = AdminModel::getAdminById($uid);
        ajax_return_ok($info);
    }

    /**
     * 新增/保存
     *
     * @throws
     * @route('admin/save')
     */
    public function save()
    {
        $id = input('id', 0, 'intval');
        $password = input('password', '', 'trim');
        //接收数据
        $data = [
            'groupId' => input('groupId', '', 'trim'),
            'userName' => input('userName', '', 'trim'),
            'realName' => input('realName', '', 'trim'),
            'avatar' => input('avatar', '', 'trim'),
            'phone' => input('phone', '', 'trim'),
            'email' => input('email', '', 'trim'),
            //'password'  => input('password', '', 'trim'),
            'regTime' => input('regTime', 0, 'int'),
            'isEnabled' => input('isEnabled', 0, 'int'),
        ];
        $validate = validate('setting.Admin');
        $result = $validate->scene('save')->check($data);
        if (!$result) {
            $error = $validate->getError();
            ajax_return_error($error);
        }
        if ($id) {
            // 更新
            if ($id == 1) {
                $data['isEnabled'] = 1;
            }
            if ($password != '') {
                $passwordSalt = random();
                $password = encrypt_pass($password, $passwordSalt);
                $data['password'] = $password;
                $data['passwordSalt'] = $passwordSalt;
            }
            $res = AdminModel::where('id', $id)->update($data);
        } else {
            // 新增
            $passwordSalt = random();
            $password = encrypt_pass($password, $passwordSalt);
            $data['password'] = $password;
            $data['passwordSalt'] = $passwordSalt;
            $res = AdminModel::create($data);
            $id = $res ? $res->id : 0;
        }
        if ($res !== false) {
            ajax_return_ok(['id' => $id], '保存成功！');
        } else {
            ajax_return_error('保存失败！');
        }
    }

    /**
     * 删除
     *
     * @route('admin/del')
     */
    public function del()
    {
        $id = input('id', 0, 'intval');
        if ($id == 0) {
            ajax_return_error('参数有误！');
        } else {
            if ($id == 1) {
                ajax_return_error('该记录不能删除！');
            }
            if (AdminModel::destroy($id)) {
                ajax_return_ok([], '删除成功！');
            } else {
                ajax_return_error('删除失败！');
            }
        }
    }

    /**
     * 批量删除
     *
     * @route('admin/delAll')
     */
    public function delAll()
    {
        $ids = input('ids', '', 'trim');
        if (empty($ids)) {
            ajax_return_error('参数有误！');
        } else {
            $ids = explode(',', $ids);
            $ids = array_diff($ids, [1]);// 排查id为1的管理员
            AdminModel::destroy($ids);
            ajax_return_ok([], '删除成功！');
        }
    }

    /**
     * 修改
     *
     * @throws
     * @route('admin/change')
     */
    public function change()
    {

        $val = input('val', '', 'int');
        $field = input('field', '', 'trim');
        $value = input('value', '', 'int');
        if (empty($field)) {
            ajax_return_error('参数有误！');
        }
        if ($val == 1 && $field == 'isEnabled') {
            ajax_return_error('不能禁用！');
        }
        $res = AdminModel::where('id', $val)->update([$field => $value]);
        if ($res !== false) {
            ajax_return_ok([], '修改成功！');
        } else {
            ajax_return_error('修改失败！');
        }

    }

    /**
     * 批量修改
     *
     * @throws
     * @route('admin/changeAll')
     */

    public function changeAll()
    {
        $val = input('val', '', 'trim');
        $field = input('field', '', 'trim');
        $value = input('value', '', 'int');
        if (empty($val) || empty($field)) {
            ajax_return_error('参数有误！');
        }
        $lists = [];
        $ids = explode(',', $val);
        foreach ($ids as $v) {
            if ($field != 'isEnabled' || $v != 1) {
                $lists[] = ['id' => $v, $field => $value];
            }
        }
        $adminModel = new AdminModel;
        $adminModel->saveAll($lists);
        ajax_return_ok([], '修改成功！');

    }

    /**
     * 修改密码
     *
     * @route('admin/setPwd')
     */
    public function setPwd()
    {
        //接收数据
        $data = [
            'oldPwd' => input('oldPwd', '', 'trim'),
            'newPwd' => input('newPwd', '', 'trim'),
            'newPwd2' => input('newPwd2', '', 'trim')
        ];
        //验证输入数据合法性
        $validate = validate('setting.Password');
        $result = $validate->check($data);
        if (!$result) {
            $error = $validate->getError();
            ajax_return_error($error);
        }
        $res = AdminModel::setPwd($this->uid, $data['newPwd'], $data['oldPwd']);
        if ($res !== false) {
            ajax_return_ok([], '修改成功！');
        } else {
            ajax_return_error('修改失败！');
        }
    }

    /**
     * 修改个人资料
     *
     * @throws
     * @route('admin/modify')
     */
    public function modify()
    {
        $id = $this->uid;
        $password = input('password', '', 'trim');
        //接收数据
        $data = [
            'realName' => input('realName', '', 'trim'),
            'avatar' => input('avatar', '', 'trim'),
            'phone' => input('phone', '', 'trim'),
            'email' => input('email', '', 'trim'),
        ];
        if ($password) {
            $passSalt = random();
            $password = encrypt_pass($password, $passSalt);
            $data['password'] = $password;
            $data['passSalt'] = $passSalt;
        }
        $validate = validate('setting.Admin');
        $result = $validate->scene('modify')->check($data);
        if (!$result) {
            $error = $validate->getError();
            ajax_return_error($error);
        }
        $res = AdminModel::where('id', $id)->update($data);
        if ($res !== false) {
            ajax_return_ok(['id' => $res], '保存成功！');
        } else {
            ajax_return_error('保存失败！');
        }
    }
}
